package com.ericsson.enap.modules.kpi.service.impl;

import com.ericsson.common.pojo.FTPInfoVO;
import com.ericsson.common.util.SFtpCarrierUtil;
import com.ericsson.enap.modules.kpi.entity.EnipMeasInfo;
import com.ericsson.enap.modules.kpi.entity.EnipMeasValue;
import com.ericsson.enap.modules.kpi.entity.ImsFiveKpi;
import com.ericsson.enap.modules.kpi.entity.VgcFifKpi;
import com.ericsson.enap.modules.kpi.service.EnipKpiFileProcess;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * CHF类型网元五分钟指标处理(電信版本讀取.log)
 */
@Component
public class KpiFileProcessCHFFIVEImpl implements EnipKpiFileProcess {

    public TreeMap<String, List<File>> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log, Date date) {
        log.info("===================================================  start download Files");
        String lastDownTime = ((VgcFifKpi)imsFiveKpi).getLastDownTime();
        FTPInfoVO ftpInfo = new FTPInfoVO();
        ftpInfo.setHost(imsFiveKpi.getIp4());
        ftpInfo.setUserName(imsFiveKpi.getUsername());
        ftpInfo.setPassword(imsFiveKpi.getPassword());
        ftpInfo.setPath(imsFiveKpi.getDownloadPath());
        ftpInfo.setPort(21);
        TreeMap<String,List<File>> fileMap = new TreeMap<>();
        List<File> fileList;
        SFtpCarrierUtil sftpCarrier = new SFtpCarrierUtil(ftpInfo, log);
        try {
            sftpCarrier.connect();
            Vector v = sftpCarrier.listFiles(ftpInfo.getPath());
            Collections.sort(v);
            if (v.size() > 0) {
                if(null!=lastDownTime&&!"".equals(lastDownTime)) {
                    Iterator it = v.iterator();
                    while (it.hasNext()) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                        String filename = entry.getFilename();
                        SftpATTRS attrs = entry.getAttrs();
                        if (!attrs.isDir()) {
                            if (filename.length() > 21 && filename.contains("counters")
                                    && (filename.substring(9,21).compareTo(lastDownTime))>0) {
                                    File tempFile = sftpCarrier.downloadFileKpi(ftpInfo.getPath(), filename, localDir, filename);
                                    if (null != tempFile) {
                                        String timeKey = filename.substring(9, 21);
                                        if (fileMap.containsKey(timeKey)) {
                                            fileMap.get(timeKey).add(tempFile);
                                        } else {
                                            fileList = new ArrayList<>();
                                            fileList.add(tempFile);
                                            fileMap.put(timeKey, fileList);
                                        }
                                    }
                            }
                        }
                    }
                }else{
                    Collections.sort(v,Collections.reverseOrder());
                    Iterator it = v.iterator();
                    while (it.hasNext()) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next();
                        String filename = entry.getFilename();
                        SftpATTRS attrs = entry.getAttrs();
                        if (!attrs.isDir()) {
                            if (filename.length() > 21 && filename.contains("counters")) {
                                    File tempFile = sftpCarrier.downloadFileKpi(ftpInfo.getPath(), filename, localDir, filename);
                                    if (null != tempFile) {
                                        String timeKey = filename.substring(9, 21);
                                        fileList = new ArrayList<>();
                                        fileList.add(tempFile);
                                        fileMap.put(timeKey, fileList);
                                        break;
                                    }
                            }
                        }
                    }
                }
            }
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            sftpCarrier.disconnect();
        }
        return fileMap;
    }

    @Override
    public File download(ImsFiveKpi imsFiveKpi, String localDir, Logger log) {
        return null;
    }

    @Override
    public List<File> download(ImsFiveKpi imsFiveKpi, String localDir, Logger log, Date date, int delay) {
        return null;
    }

    /**
     * 解析文件
     * @param files
     * @param log
     * @return
     */
    public List<EnipMeasInfo> analysis(List<File> files, Logger log){
        List<EnipMeasInfo> meansInfoList = new ArrayList<>();
        for(File file:files) {
            if(file.exists()) {
                InputStreamReader read = null;
                try {
                    read = new InputStreamReader(new FileInputStream(file));
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt;
                int lineNum=0;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    if(lineNum!=0){
                        EnipMeasInfo mi = new EnipMeasInfo();
                        Map<String, String> mtMap = new HashMap<>();
                        String []arrStr=lineTxt.split(",");
                        mi.setBeginTime(arrStr[0]);
                        mi.setJobId(arrStr[2]);
                        String text = arrStr[5].replace("jcl0922/CT_OLM_SMF01_TOCHF_20210922.","").replace("jcl0922/CT_OLM_SMF02_TOCHF_20210922.","");
                        mtMap.put(arrStr[2]+"_"+text, String.valueOf(lineNum));
                        mi.setMeasTypeMap(mtMap);

                        EnipMeasValue measValue = new EnipMeasValue();
                        Map<String, String> rMap = new HashMap<>();
                        if("".equals(arrStr[6])){
                            rMap.put(String.valueOf(lineNum), "0");
                        }else {
                            rMap.put(String.valueOf(lineNum), arrStr[6]);
                        }
                        String measObjLdn=arrStr[3]+arrStr[4];
                        measValue.setMeasObjLdn(measObjLdn);
                        measValue.setRMap(rMap);

                        Map<String, EnipMeasValue> mvMap = mi.getMeasValueMap();
                        mvMap.put(measObjLdn, measValue);

                        meansInfoList.add(mi);
                    }
                    lineNum++;
                }
                    bufferedReader.close();
                    read.close();
                } catch (Exception e) {
                    log.error("file not found CHFFIVE analysis OR read ERROR");
                }
            }
        }
        return meansInfoList;
    }

    @Override
    public boolean needUncompress() {
        return false;
    }

    @Override
    public NetType getNetType() {
        return NetType.CHF;
    }
}
